package geektime.io.netty.homework;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.*;

/**
 * 模拟客户端的处理类
 */
public class DemoClientHandler extends ChannelInboundHandlerAdapter {

    private ByteBuf byteBuf = new UnpooledByteBufAllocator(false).heapBuffer();
    private Scanner scanner = new Scanner(System.in);

    // 和服务端连接成功后的处理方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Connection established.");
    }

    // 读取服务端信息的方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 接收并打印服务端的响应结果
        receiveMsgFromServer(ctx, (ByteBuf) msg);
    }

    // 读取服务端信息动作完成后的方法
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        sendMsgToServer(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    private void sendMsgToServer(ChannelHandlerContext ctx) {
        System.out.print("C: ");
        String msg = scanner.nextLine();
        byteBuf.writeBytes(msg.getBytes());
        ctx.writeAndFlush(byteBuf);
    }

    private void receiveMsgFromServer(ChannelHandlerContext ctx, ByteBuf msg) {
        byteBuf = msg;
        byte[] bytes = new byte[byteBuf.writerIndex()];
        byteBuf.readBytes(bytes);
        String strMsg = new String(bytes);
        System.out.println("S: " + strMsg);
        // 如果接受到了退出信号，则退出
        if ("221 Bye".equals(strMsg)) {
            ctx.close();
            System.exit(0);
        }
    }

}
